package com.httpdemo.http_teaching_server.controller;

import com.httpdemo.http_teaching_server.model.User;
import com.httpdemo.http_teaching_server.repository.UserRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.httpdemo.http_teaching_server.config.JwtConfig;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {
//    private static final Key JWT_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    @Autowired
    private UserRepository userRepository;
    /* 1️⃣ Basic 登录示例 */
    @GetMapping("/basic")
    public Map<String, String> basic(@RequestHeader("Authorization") String auth) {
        if (!"Basic dXNlcjpwYXNz".equals(auth)) { // user:pass Base64
            return Map.of("error", "Basic Auth 错误");
        }
        return Map.of("message", "Basic 登录成功");
    }


    // 登录：增加过期时间
    @PostMapping("/jwt/login")
    public Map<String, String> jwtLogin(@RequestBody Map<String, String> body) {
        String username = body.get("username");
        String password = body.get("password");

        User user = userRepository.findByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            return Map.of("error", "用户名或密码错误");
        }

        Date now = new Date();
        String token = Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(new Date(now.getTime() + 1000 * 60 * 60 * 2)) // 2 小时
                .signWith(JwtConfig.KEY)
                .compact();

        return Map.of("token", token);
    }
    /* 3️⃣ JWT 受保护资源 */
    //   解析：增加格式校验
    @GetMapping("/jwt/me")
    public Map<String, Object> me(@RequestHeader("Authorization") String auth) {
        if (auth == null || !auth.startsWith("Bearer ")) {
            throw new IllegalArgumentException("Authorization header 格式错误");
        }
        String token = auth.substring(7);
        String username = Jwts.parserBuilder()
                .setSigningKey(JwtConfig.KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        return Map.of("username", username, "type", "JWT 受保护");
    }
    /* 4️⃣ Cookie 示例 */
    @PostMapping("/cookie/login")
    public ResponseEntity<Void> cookieLogin() {
        return ResponseEntity.ok()
                .header(HttpHeaders.SET_COOKIE, "token=abc123; Path=/; HttpOnly")
                .build();
    }

    @GetMapping("/cookie/me")
    public Map<String, Object> cookieMe(@CookieValue("token") String token) {
        return Map.of("username", "cookieUser", "token", token);
    }
}